package com.haifeng.asms.auth.entity;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.annotation.TableField;
import com.haifeng.asms.dao.model.dto.PermissionDto;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *  UserDetails返回用户信息
 * </p>
 *
 * @author: Haifeng
 * @date: 2020-06-22
 */
@Data
public class UserDetailsEntity implements UserDetails {

    @ApiModelProperty(value = "主键")
    private Long id;

    @ApiModelProperty(value = "用户名")
    private String username;

    @JSONField(serialize = false)
    @ApiModelProperty(value = "密码，加密存储")
    private String password;

    @ApiModelProperty(value = "账户是否过期：0-过期；1-未过期")
    @TableField("account_non_expired")
    private boolean accountNonExpired;

    @ApiModelProperty(value = "密码是否过期：0-过期；1-未过期")
    @TableField("credentials_non_expired")
    private boolean credentialsNonExpired;

    @ApiModelProperty(value = "是否锁定：0-锁定；1-未锁定")
    @TableField("account_non_locked")
    private boolean accountNonLocked;

    @ApiModelProperty(value = "是否可用：0-不可用；1-可用")
    private boolean enabled;

    @ApiModelProperty(value = "权限集合")
    private Set<PermissionDto> permissionList = new HashSet<>();

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> grantedAuthorities = CollectionUtil.newArrayList();
        if (CollUtil.isNotEmpty(permissionList)) {
            permissionList.forEach(permissionDto -> {
                if (permissionDto != null && permissionDto.getPermissionCode() != null) {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permissionDto.getPermissionUrl());
                    grantedAuthorities.add(grantedAuthority);
                }
            });
        }
        return grantedAuthorities;
    }
}
